package io.mqttpush.mqttclient.pack;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.mqttpush.mqttserver.beans.ConstantBean;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DecoderException;

/**
 * 自定义协议的解码器
 * @author tianzhenjiu
 *
 */
public class MqttPackExtDecoderByte extends ByteToMessageDecoder{

	
	Logger logger=LoggerFactory.getLogger(getClass());
	
	
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	
		
		boolean nextChannelPorcess=false;
		if(in.readableBytes()<13) {
			nextChannelPorcess=true;
		}
		
		if(!nextChannelPorcess) {
			int magic=in.readInt();
			if(magic!=MqttPackExt.magicNum) {
				nextChannelPorcess=true;
			}
		}
		
		
		if(nextChannelPorcess) {

			in.resetReaderIndex();
			in.retain();
			ctx.fireChannelRead(in);
			return;
		}
		
		
		int iplen=in.readInt();
		byte[] ipbytes=null;
		if(iplen>0) {			
			ipbytes=new byte[iplen];
			in.readBytes(ipbytes);
		}
		
		int sport=in.readInt();
		int headerlen=in.readInt();
		if(in.readableBytes()<=headerlen) {
			logger.warn("报文格式不对");
			throw new DecoderException("报文长度不够");
		}
		
		byte[] bs=new byte[headerlen];
		in.readBytes(bs);
		
		MqttPackExt mqttPackExt=new MqttPackExt();
		
		if(ipbytes!=null) {			
			mqttPackExt.fromIp=new String(ipbytes);
		}
		mqttPackExt.sport=sport;
		mqttPackExt.headerLen=headerlen;
		mqttPackExt.headerString=new String(bs);
		
		ByteBuf mqttBuf=ctx.alloc().buffer(in.readableBytes());
		
		in.readBytes(mqttBuf);
		
		mqttPackExt.mqttMsg=mqttBuf;
		
		ctx.channel().attr(ConstantBean.channelExtMsg).set(mqttPackExt);
		
		out.add(mqttBuf);
		
		
	}
	


}
